package com.basic.modules.nykf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.common.utils.*;
import com.basic.modules.nykf.dao.CustomerShopBusinessDao;
import com.basic.modules.nykf.dao.RenewManageDao;
import com.basic.modules.nykf.dao.RenewShouDao;
import com.basic.modules.nykf.dao.RenewTuiDao;
import com.basic.modules.nykf.entity.CustomerShopBusinessEntity;
import com.basic.modules.nykf.entity.RenewListEntity;
import com.basic.modules.nykf.entity.RenewShouEntity;
import com.basic.modules.nykf.entity.RenewTuiEntity;
import com.basic.modules.nykf.service.CustomerShopBusinessService;
import com.basic.modules.nykf.service.RenewManageService;
import com.basic.modules.nykf.service.RenewShouService;
import com.basic.modules.nykf.service.RenewTuiService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Service
public class RenewManageServiceImpl extends ServiceImpl<RenewManageDao, RenewListEntity> implements RenewManageService {

    @Lazy
    @Autowired
    CustomerShopBusinessDao customerShopBusinessDao;

    @Autowired
    CustomerShopBusinessService customerShopBusinessService;

    @Autowired
    RenewManageDao renewManageDao;

    @Autowired
    RenewShouService renewShouService;

    @Autowired
    RenewTuiService renewTuiService;

    @Autowired
    RenewShouDao renewShouDao;

    @Autowired
    RenewTuiDao renewTuiDao;

    @Override
    public PageUtils getRenewManageList(ParamsModel<RenewListEntity> params) {
        IPage<RenewListEntity> page = new Query<RenewListEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
        IPage<RenewListEntity> renewManageList = renewManageDao.getRenewManageList(page, params.getCondition());
        return new PageUtils(renewManageList);
    }

    @Override
    @Transactional
    public R postSkList(List<RenewShouEntity> renewShouEntities, Long customerId, String sfmsVal, String batchId, Long customerShopBusinessId, String xfrq) {
        boolean isSk = false;
        for (int i = 0; i < renewShouEntities.size(); i++) {
            ObjectMapper objectMapper = new ObjectMapper();
            RenewShouEntity renewShouEntity = objectMapper.convertValue(renewShouEntities.get(i), RenewShouEntity.class);

            if ("已收款".equals(renewShouEntity.getSkztVal())) {
                isSk = true;
            }
            Long id = renewShouEntity.getId();
            if (id == null) {
                // 支付记录新增
                renewShouEntity.setBatchId(batchId);
                renewShouService.save(renewShouEntity);
            } else {
                // 支付记录修改
                renewShouService.updateById(renewShouEntity);
            }
        }

        // 支付完成之后,如果有已收款的数据,将支付状态改为已支付
        if (sfmsVal.indexOf("合并") != -1) {
            // 如果是合并收费,根据客户ID、收费模式、续费日期去修改
            UpdateWrapper<RenewListEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper
                    .eq("sfms_val", sfmsVal)
                    .eq("customer_id", customerId)
                    .eq("xfrq", xfrq)
                    .set("batch_id", batchId);
            if (isSk) {
                updateWrapper
                        .set("zfzt_val", "已支付")
                        .set("zfzt_name", "已支付");
            }
            this.update(updateWrapper);
        } else {
            // 如果是单独收费,根据业务ID、续费日期去修改
            UpdateWrapper<RenewListEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper
                    .eq("customer_shop_business_id", customerShopBusinessId)
                    .eq("xfrq", xfrq)
                    .set("batch_id", batchId);
            if (isSk) {
                updateWrapper
                        .set("zfzt_val", "已支付")
                        .set("zfzt_name", "已支付");
            }
            this.update(updateWrapper);
        }
        // 修改业务表业务底薪
        updateYwdxByShouAndTui(batchId, customerShopBusinessId, customerId, sfmsVal);
        return R.ok();
    }

    @Override
    public R postTkList(List<RenewTuiEntity> renewTuiEntities, Long customerId, String sfmsVal, String batchId, Long customerShopBusinessId) {
        for (int i = 0; i < renewTuiEntities.size(); i++) {
            ObjectMapper objectMapper = new ObjectMapper();
            RenewTuiEntity renewTuiEntity = objectMapper.convertValue(renewTuiEntities.get(i), RenewTuiEntity.class);
            Long id = renewTuiEntity.getId();
            if (id == null) {
                // 退款记录新增
                renewTuiEntity.setBatchId(batchId);
                renewTuiService.save(renewTuiEntity);
            } else {
                // 支付记录修改
                renewTuiService.updateById(renewTuiEntity);
            }
        }
        // 修改业务表业务底薪
        updateYwdxByShouAndTui(batchId, customerShopBusinessId, customerId, sfmsVal);
        return R.ok();
    }

    @Override
    @Transactional
    public R postXfList(Map map) {
        System.out.println(map);
        Long customerId = Long.parseLong(map.get("customerId").toString());
        String sfmsVal = null;
        // 校验
        if (map.get("xfkssj") == null || map.get("xfjssj") == null || DateUtils.isValidDateTime(map.get("xfkssj").toString()) == false || DateUtils.isValidDateTime(map.get("xfjssj").toString()) == false) {
            return R.error("请输入续费开始时间和续费结束时间");
        }

        // 续费的开始时间不能小于等于当前的业务结束时间
        Date xfkssj = DateUtils.stringToDate(map.get("xfkssj").toString(), "yyyy-MM-dd");
        Date xfjssj = DateUtils.stringToDate(map.get("xfjssj").toString(), "yyyy-MM-dd");
        Date ywjsrq = DateUtils.stringToDate(map.get("ywjsrq").toString(), "yyyy-MM-dd");

        if (xfkssj.compareTo(ywjsrq) <= 0) {
            return R.error("续费开始日期不能小于等于当前的业务结束日期");
        }

        List<CustomerShopBusinessEntity> customerShopBusinessEntityList = (List<CustomerShopBusinessEntity>) map.get("xfList");
        // 批次ID
        String batchId = map.get("batchId").toString();

        ObjectMapper objectMapper = new ObjectMapper();
        if (customerShopBusinessEntityList.size() > 0) {
            sfmsVal = objectMapper.convertValue(customerShopBusinessEntityList.get(0), CustomerShopBusinessEntity.class).getSfmsVal();
        }

        for (int i = 0; i < customerShopBusinessEntityList.size(); i++) {
            CustomerShopBusinessEntity customerShopBusinessEntity = objectMapper.convertValue(customerShopBusinessEntityList.get(i), CustomerShopBusinessEntity.class);
            customerShopBusinessEntity.setYwkssj(xfkssj);
            customerShopBusinessEntity.setYwjssj(xfjssj);
            customerShopBusinessEntity.setYwdx(new BigDecimal(0));

            // 先把业务续费信息新增到续费明细表
            RenewListEntity renewListEntity = new RenewListEntity(customerShopBusinessEntity, "续费订单", "待支付", "待续费");
            renewListEntity.setCustomerId(customerId);
            renewListEntity.setYwdx(new BigDecimal(0));
            // 计算续费日期
            Date xfrq = customerShopBusinessService.calcXfrq(customerId, renewListEntity.getYwjsrq());
            renewListEntity.setXfrq(xfrq);
            this.save(renewListEntity);

            // 然后把这个业务的业务ID初始化成0
            Long customerShopBusinessId = customerShopBusinessEntity.getCustomerShopBusinessId();
            UpdateWrapper<CustomerShopBusinessEntity> updateWrapper1 = new UpdateWrapper<>();
            updateWrapper1
                    .eq("customer_shop_business_id", customerShopBusinessId)
                    .set("ywdx", 0);
            customerShopBusinessService.update(updateWrapper1);

            // 然后把这个批次的订单状态修改为已支付已续费
            UpdateWrapper<RenewListEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper
                    .eq("batch_id", batchId)
                    .eq("xfzt_val", "待续费")
                    .set("xfzt_val", "续费成功")
                    .set("xfzt_name", "续费成功");
            this.update(updateWrapper);

            // 然后修改业务数据
            customerShopBusinessDao.updateById(customerShopBusinessEntity);
        }

        //  处理咨询量
        if (sfmsVal != null && sfmsVal.indexOf("合并") != -1) {
            customerShopBusinessService.setZxlByCustomerIdAndSfms_set(customerId, sfmsVal);
        }
        return R.ok();
    }

    /**
     * 根据批次ID查询出所有的收款记录和退款记录,然后进行相减得出最终的业务底薪并更新业务表
     *
     * @return
     */
    public R updateYwdxByShouAndTui(String batchId, Long customerShopBusinessId, Long customerId, String sfmsVal) {
        // 计算业务底薪
        BigDecimal skjeSum = renewShouDao.getSkjeSumByBatchId(batchId);
        BigDecimal tkjeSum = renewTuiDao.getTkjeSumByBatchId(batchId);

        if (ObjectUtil.isNull(skjeSum)) {
            skjeSum = new BigDecimal(0);
        }

        if (ObjectUtil.isNull(tkjeSum)) {
            tkjeSum = new BigDecimal(0);
        }

        // 税前金额
        BigDecimal ywdx = skjeSum.subtract(tkjeSum);

        // 税后金额
        BigDecimal divisor = new BigDecimal("1.06");
        BigDecimal shYwdx = ywdx.divide(divisor, 2, RoundingMode.HALF_UP);

        // 先改续费表
        UpdateWrapper<RenewListEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .eq("batch_id", batchId)
                .eq("customer_shop_business_id", customerShopBusinessId)
                .set("ywdx", ywdx);
        this.update(updateWrapper);

        UpdateWrapper<RenewListEntity> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1
                .eq("batch_id", batchId)
                .isNull("ywdx")
                .set("ywdx", 0);
        this.update(updateWrapper1);

        if (sfmsVal.indexOf("合并") != -1) {
            // 合并收费,改合并表
            Map map = new HashMap();
            map.put("customerId", customerId);
            map.put("ywdx", ywdx);
            map.put("shYwdx",shYwdx);
            map.put("sfmsVal", sfmsVal);
            customerShopBusinessService.setYwdxByCustomerIdAndSfms_set(map);
        } else {
            // 单独收费,直接改业务表
            CustomerShopBusinessEntity customerShopBusinessEntity = new CustomerShopBusinessEntity();
            customerShopBusinessEntity.setCustomerShopBusinessId(customerShopBusinessId);
            customerShopBusinessEntity.setYwdx(ywdx);
            customerShopBusinessEntity.setShYwdx(shYwdx);
            customerShopBusinessService.updateById(customerShopBusinessEntity);
        }
        return R.ok();
    }

    @Override
    public R getRenewShouList(RenewShouEntity renewShouEntity) {
        String batchId = renewShouEntity.getBatchId();
        QueryWrapper<RenewShouEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("batch_id", batchId);
        List<RenewShouEntity> list = renewShouService.list(queryWrapper);
        return R.ok(list);
    }

    @Override
    public R getRenewTuiList(RenewTuiEntity renewTuiEntity) {
        String batchId = renewTuiEntity.getBatchId();
        QueryWrapper<RenewTuiEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("batch_id", batchId);
        List<RenewTuiEntity> list = renewTuiService.list(queryWrapper);
        return R.ok(list);
    }

    @Override
    public R getXfywListBySfmsValAndCustomerId(RenewListEntity renewListEntity) {
        // 客户ID和收费模式(分组)
        Long customerId = renewListEntity.getCustomerId();
        String sfmsVal = renewListEntity.getSfmsVal();
        // 找出这个客户对应收费模式(分组)的业务数据
        Map map = new HashMap();
        map.put("customerId", customerId);
        map.put("sfmsVal", sfmsVal);
        List<CustomerShopBusinessEntity> list = customerShopBusinessDao.getXfywListBySfmsValAndCustomerId(map);
        return R.ok(list);
    }
}